#coding:utf-8

import httplib2
from logger_factory import LOG_INFO, LOG_ERR

class HttpUtil(object):

    MAX_TRY_TIMES = 3

    @classmethod
    def get_for_object(cls, url, username, password):
        for i in xrange(cls.MAX_TRY_TIMES):
            try:
                http_client = cls.get_http_client(username, password)
                resp, content = http_client.request(url)
                if resp.get("status") != "200":
                    raise Exception("failed get object from url, "
                                    "status code: %s, excepted: 200" % resp.get("status"))

                return content
            except Exception, e:
                if i != cls.MAX_TRY_TIMES - 1:
                    continue
                raise

    @classmethod
    def get_http_client(cls, username, password):
        client = httplib2.Http(timeout = 10, disable_ssl_certificate_validation=False)
        client.add_credentials(username, password)
        return client

    @classmethod
    def get_default_http_client(cls):
        return httplib2.Http()
